// store/modules/user.js
import { reqGetUserInfo } from "@/api";
const userModule = {
  namespaced: true,
  state: {
    token: sessionStorage.getItem('token') || '',
    userInfo:{},
    userForm: {
      userId: "",
      userType: "",
      username: "",
      realName: "",
      email: "",
      major: "",
      qqNumber: "",
      phoneNumber: "",
      university: "",
      userProfile: "",
      avatar: "",
    },
  },
  mutations: {
    // 批量替换 userForm
    SET_USER_FORM(state, formData) {
      state.userForm = { ...formData };
    },
    GETTOKEN(state, data) {
      state.token = data;
    },
    SET_USER_INFO(state, data) {
      state.userInfo = data;
    },
    CLEAR_USER_INFO(state) {
      state.userInfo = {};
    },
  },
  actions: {
    getToken({commit},data){
      commit("GETTOKEN", data);
    },
    // 初始化用户数据
    async initUserInfo({ commit, dispatch }) {
      try {
        const res = await reqGetUserInfo();
        if (res.code === 200) {
          commit("SET_USER_FORM", res.data);
        }
      } catch (error) {
        dispatch("handleError", error);
      }
    },
    // 错误处理
    handleError({ commit }, error) {
      console.error(error);
      this.$message.error(error.message || "操作失败");
    },
  },
  getters: {},
};
export default userModule;
